WTMO-dev
AI
CV
basic
DL
basic
ML
basic
NLP
basic
dspy
hugging face
llama index
ollama
C++
basic
COMPUTER SCIENCE
basic
ETC
GIT
Blog
basic
IDE
VSC
python
setting
JAVA
basic
MATH
Basic
Statistic
NETWORK
basic
OS
Window
WSL
basic
basic
PROJECT
PYTHON
Advance
Basic
Framework
Django
FastAPI
Library
Module
Home
PROJECT PRACTICE
Crawling
EDA
Kaggle
Python
CV
Contact
Copyright © 2024
WTMO-dev
Home
>
AI
>
NLP
> llama index
Now Loading ...
llama index
Llamaindex ChatBot
what is ChatBot Chat bot은 사용자가 질문을 하면 원하는 답변을 해주는 것을 이야기합니다. 아래는 Chat bot을 활용한 일부 예시 입니다. simple example system prompt example templet example llama-parser, faiss example
AI
/
NLP
/
llama index
· 2024-03-19
Llamaindex RAG
what is RAG RAG는 Retrieval Augmented Generation의 약자로 언어 모델의 응답이 조금 더 좋은 결과를 도출하기 위한 것입니다. 이는 추가적인 데이터들을 기반으로 좋은 응답 결과를 보장하게 됩니다. 아래는 RAG를 활용한 일부 예시 입니다. simple example SentenceWindowNodeParser example llama-parser example llama-parser, faiss example
AI
/
NLP
/
llama index
· 2024-03-18
Llamaindex retriever
what is retriever retriever는 검색엔진과 같은 역활을 합니다. index에 있는 값들을 query를 이용하여 관련된 내용을 추출해 내줍니다. how to use retriever 간단하게 사용하는 방식은 아래와 같이 사용할 수 있습니다. {% highlight shell %} retriever = index.as_retriever() nodes = retriever.retrieve(“{question}”) {% endhighlight %} how to use retriever advance retriever를 사용하는 고급 기법이 아래와 같이 존재합니다. 이방식은 index의 종류별로 상세하게 세팅을 하는 방법이며 retriever modes를 참고하여 다양한 retriever를 만들어 볼 수 있습니다. {% highlight shell %} retriever = summary_index.as_retriever( retriever_mode=”llm”, choice_batch_size=5, ) {% endhighlight %}
AI
/
NLP
/
llama index
· 2024-03-15
Llamaindex pipeline
pipeline(W. document, node) documentd와 node를 하나의 pipeline으로 엮어서 사용하는 방식을 말합니다. {% highlight python %} import re from llama_index.core import Document from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.node_parser import SentenceSplitter from llama_index.core.ingestion import IngestionPipeline from llama_index.core.schema import TransformComponent class TextCleaner(TransformComponent): def call(self, nodes, **kwargs): for node in nodes: node.text = re.sub(r”[^0-9A-Za-z ]”, “”, node.text) return nodes use in a pipeline pipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_size=25, chunk_overlap=0), TextCleaner(), OpenAIEmbedding(), ], ) nodes = pipeline.run(documents=[Document.example()]) {% endhighlight %} pipeline(W. document, node, index) {% highlight python %} from llama_index.core import VectorStoreIndex from llama_index.core.extractors import ( TitleExtractor, QuestionsAnsweredExtractor, ) from llama_index.core.ingestion import IngestionPipeline from llama_index.core.node_parser import TokenTextSplitter transformations = [ TokenTextSplitter(chunk_size=512, chunk_overlap=128), TitleExtractor(nodes=5), QuestionsAnsweredExtractor(questions=3), ] global from llama_index.core import Settings Settings.transformations = [text_splitter, title_extractor, qa_extractor] per-index index = VectorStoreIndex.from_documents( documents, transformations=transformations ) {% endhighlight %}
AI
/
NLP
/
llama index
· 2024-03-14
Llamaindex embedding
what is embedding embedding은 입력을 받은 document or node에 있어서 vector로 나타내는것입니다. 이를 통하여 코사인 유사도와 같이 문서들간의 유사성을 계산하여 문서를 효율적으로 사용할 수 있게 됩니다. llama는 기본적으로 코사인 유사도를 사용하고 있으며 아래의 방식으로 다양한 embedding을 사용해 볼 수 있습니다. W. OpenAI OpenAI에서 사용하는 embedding을 사용하려면 아래와 같이 사용하면 됩니다. 하지만 유료인점을 참고해야합니다. {% highlight shell %} pip install llama-index-embeddings-openai {% endhighlight %} {% highlight python %} import os OPENAI_API_TOKEN = “sk-“ os.environ[“OPENAI_API_KEY”] = OPENAI_API_TOKEN from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core import Settings global Settings.embed_model = OpenAIEmbedding(embed_batch_size=42) # default is 10 per-index index = VectorStoreIndex.from_documents(documents, embed_model=embed_model) {% endhighlight %} W. hugging face hugging face를 사용하여 enbedding을 하는 방식은 아래와 같습니다. {% highlight shell %} pip install llama-index-embeddings-huggingface {% endhighlight %} {% highlight python %} from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import Settings Settings.embed_model = HuggingFaceEmbedding( model_name=”BAAI/bge-small-en-v1.5” ) {% endhighlight %} W. hugging face(W. ONNX) hugging face를 ONNX로 사용하는 법은 아래와 같습니다. {% highlight shell %} pip install transformers optimum[exporters] pip install llama-index-embeddings-huggingface-optimum {% endhighlight %} {% highlight python %} from llama_index.embeddings.huggingface_optimum import OptimumEmbedding OptimumEmbedding.create_and_save_optimum_model( “BAAI/bge-small-en-v1.5”, “./bge_onnx” ) Settings.embed_model = OptimumEmbedding(folder_name=”./bge_onnx”) {% endhighlight %} W. langchain langchain에서 지원하는 다양한 embedding을 사용할 수 있습니다. langchain embeddings list {% highlight shell %} pip install llama-index-embeddings-langchain {% endhighlight %} {% highlight python %} from langchain.embeddings.huggingface import HuggingFaceBgeEmbeddings from llama_index.core import Settings Settings.embed_model = HuggingFaceBgeEmbeddings(model_name=”BAAI/bge-base-en”) {% endhighlight %} W. custom embedding 위에서 사용할 수 있는 다양한 embedding 이외에 다른 embedding을 직접 만들어서 활용하려면 아래와 같이 해볼 수 있습니다. {% highlight python %} from typing import Any, List from InstructorEmbedding import INSTRUCTOR from llama_index.core.embeddings import BaseEmbedding class InstructorEmbeddings(BaseEmbedding): def init( self, instructor_model_name: str = “hkunlp/instructor-large”, instruction: str = “Represent the Computer Science documentation or question:”, kwargs: Any, ) -> None: self._model = INSTRUCTOR(instructor_model_name) self._instruction = instruction super().__init__(kwargs) def _get_query_embedding(self, query: str) -> List[float]: embeddings = self._model.encode([[self._instruction, query]]) return embeddings[0] def _get_text_embedding(self, text: str) -> List[float]: embeddings = self._model.encode([[self._instruction, text]]) return embeddings[0] def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: embeddings = self._model.encode( [[self._instruction, text] for text in texts] ) return embeddings async def _get_query_embedding(self, query: str) -> List[float]: return self._get_query_embedding(query) async def _get_text_embedding(self, text: str) -> List[float]: return self._get_text_embedding(text) {% endhighlight %} other embeddings 이외에도 다양한 embedding을 사용할 수 있으며 아래는 지원하는 embedding list 입니다. embeddings list
AI
/
NLP
/
llama index
· 2024-03-13
Llamaindex index
what is index index는 RAG와 같이 검색을 하는 구조에서 빠르게 검색하기 위한 구조입니다. 추가적인 활용처로는 채팅봇과 같이 QA로 사용할 수 있습니다. vector store index index 기법에서 가장 흔하게 사용이 되는 방법입니다. 이는 vector store를 활용하여 indexing을 하는 방법입니다. 아래와 같이 document을 바로 활용하는 방법과 node를 활용하는 방법 2가지로 이루어져 있습니다. {% highlight python %} from llama_index.core import VectorStoreIndex index = VectorStoreIndex.from_documents(documents) {% endhighlight %} {% highlight python %} from llama_index.core.schema import TextNode node1 = TextNode(text=”", id_="") node2 = TextNode(text="", id_="") nodes = [node1, node2] index = VectorStoreIndex(nodes) {% endhighlight %} default vectorstore이외에도 다양한 custom vectorstore를 사용할 수 있으며 아래는 간단한 예시를 나타냅니다. {% highlight python %} import pinecone from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.vector_stores.pinecone import PineconeVectorStore init pinecone pinecone.init(api_key=”", environment="") pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) construct vector store and customize storage context storage_context = StorageContext.from_defaults( vector_store=PineconeVectorStore(pinecone.Index(“quickstart”)) ) Load documents and build index documents = SimpleDirectoryReader( “../../examples/data/paul_graham” ).load_data() index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) {% endhighlight %} other index guides vector store가 가장 흔한 indexing 기법이지만 그 이외에도 아래와 같이 다양한 기법들이 있습니다. other index guides W. other embedding module 기본적으로 llama에서 제공하는 embedding으로 동작이 되지만 다른 embedding을 사용하고 싶으면 아래를 참고하여 변경이 가능합니다. embedding module pipeline documents advance(1)와 nodes advance(1)까지 확인 이후 pipeline을 아래와 같이 도입 가능합니다. document node index pipeline
AI
/
NLP
/
llama index
· 2024-03-12
Llamaindex nodes Advance(1)
create node by async node를 만들때 다음과 같이 비동기로 만들 수 있습니다. {% highlight python %} from llama_index.core.node_parser import SentenceSplitter node_parser = SentenceSplitter(chunk_size=512) nodes = await node_parser.acall(documents) {% endhighlight %} file base node parser 노드를 생성하는데 있어서 document들이 다양한 형태의 데이터를 가질 수 있으며, 각 데이터에 최적화된 node parser를 사용하는것이 성능에 영향을 미칠 수 있습니다. simple file 가장 기본적인 형태의 txt와 같은 파일에 적절한 파서입니다. 이는 flat document 와 같이 활용하기에 적합합니다. {% highlight python %} from llama_index.core.node_parser import SimpleFileNodeParser parser = SimpleFileNodeParser() md_nodes = parser.get_nodes_from_documents(md_docs) {% endhighlight %} html file HTML 파일을 사용하는데 최적화된 파서입니다. tag들을 기본적으로 제공하며 custom tag를 세팅할 수 있습니다. {% highlight python %} from llama_index.core.node_parser import HTMLNodeParser parser = HTMLNodeParser(tags=[“p”, “h1”]) # optional list of tags nodes = parser.get_nodes_from_documents(html_docs) {% endhighlight %} json file JSON 파일을 사용하는데 최적화된 파서입니다. {% highlight python %} from llama_index.core.node_parser import JSONNodeParser parser = JSONNodeParser() nodes = parser.get_nodes_from_documents(json_docs) {% endhighlight %} markdown file markdown 파일을 사용하는데 최적화된 파서입니다. {% highlight python %} from llama_index.core.node_parser import MarkdownNodeParser parser = MarkdownNodeParser() nodes = parser.get_nodes_from_documents(markdown_docs) {% endhighlight %} text base node parser 노드를 생성하는데 있어서 text를 기반으로 생성이 필요한 경우 아래의 방식을 사용할 수 있습니다. code splitter code 파일을 사용하는데 최적화된 파서입니다. 지원되는 code 목록은 다음과 같습니다. available code file {% highlight python %} from llama_index.core.node_parser import CodeSplitter splitter = CodeSplitter( language=”python”, chunk_lines=40, # lines per chunk chunk_lines_overlap=15, # lines overlap between chunks max_chars=1500, # max chars per chunk ) nodes = splitter.get_nodes_from_documents(documents) {% endhighlight %} langchain splitter langchain에서 사용하는 textsplitter를 사용할 수 있는 파서입니다. {% highlight python %} from langchain.text_splitter import RecursiveCharacterTextSplitter from llama_index.core.node_parser import LangchainNodeParser parser = LangchainNodeParser(RecursiveCharacterTextSplitter()) nodes = parser.get_nodes_from_documents(documents) {% endhighlight %} 지원하지 않는 langchain parser의 경우 아래와 같이 생성하여 사용할 수 있습니다. create langchain parser sentence splitter 문장과 문장의 끊어짐을 보장하며 분할을 할 수 있는 파서입니다. {% highlight python %} from llama_index.core.node_parser import SentenceSplitter splitter = SentenceSplitter( chunk_size=1024, chunk_overlap=20, ) nodes = splitter.get_nodes_from_documents(documents) {% endhighlight %} sentence window splitter sentence splitter와 유사하지만 해당 노드 주변의 window_size만큼의 값을 가지게 됩니다. 이것은 다음 예시와 같이 활용이 가능합니다. MetadataReplacementNodePostProcessor {% highlight python %} import nltk from llama_index.core.node_parser import SentenceWindowNodeParser node_parser = SentenceWindowNodeParser.from_defaults( # how many sentences on either side to capture window_size=3, # the metadata key that holds the window of surrounding sentences window_metadata_key=”window”, # the metadata key that holds the original sentence original_text_metadata_key=”original_sentence”, ) {% endhighlight %} semantic splitter 고정된 크기의 chunk로 node가 구성이 되지만, embedding을 활용하여 유사성을 고려한 방식으로 효과적인 방식입니다. {% highlight python %} from llama_index.core.node_parser import SemanticSplitterNodeParser from llama_index.embeddings.openai import OpenAIEmbedding embed_model = OpenAIEmbedding() splitter = SemanticSplitterNodeParser( buffer_size=1, breakpoint_percentile_threshold=95, embed_model=embed_model ) {% endhighlight %} token splitter token 크기에 기반하여 chunking을 하는 방식입니다. {% highlight python %} from llama_index.core.node_parser import TokenTextSplitter splitter = TokenTextSplitter( chunk_size=1024, chunk_overlap=20, separator=” “, ) nodes = splitter.get_nodes_from_documents(documents) {% endhighlight %} relation base node parser 노드를 생성하는데 있어서 관계성을 기반으로 생성이 필요한 경우 아래의 방식을 사용할 수 있습니다. hierarchical splitter 계층 구조로 chunking을 진행하여, 하위 레벨의 node는 상위 레벨의 node와 같이 활용 되어 좋은 결과를 도출할 수 있습니다. 다음의 예시와 같이 활용하면 적절합니다. AutoMergingRetriever {% highlight python %} from llama_index.core.node_parser import HierarchicalNodeParser node_parser = HierarchicalNodeParser.from_defaults( chunk_sizes=[2048, 512, 128] ) {% endhighlight %} pipeline documents advance(1)까지 확인 이후 pipeline을 아래와 같이 도입 가능합니다. document node pipeline
AI
/
NLP
/
llama index
· 2024-03-11
Llamaindex nodes
what is nodes 노드는 documents를 텍스트, 이미지 등등의 각 chunk로 나누는 것을 의미합니다. 이렇게 생성된 노드는 metadata정보와 관계도 정보가 포함되어 있습니다. how to use nodes(W. documents) 아래의 방식으로 node를 활용하기 위하여 documents를 사용할 수 있어야합니다. 아래의 링크를 참고해주세요. documents documents를 활용하여 간단하게 node를 사용하려면 다음과 같이 사용하면 됩니다. {% highlight python %} from llama_index.core.node_parser import SentenceSplitter parser = SentenceSplitter() nodes = parser.get_nodes_from_documents(documents) {% endhighlight %} how to use nodes(custom text) 아래의 방식으로 각각의 text를 수동으로 node를 만들어 줄 수도 있습니다.(고급) {% highlight python %} from llama_index.core.schema import TextNode, NodeRelationship, RelatedNodeInfo node1 = TextNode(text=”", id_="") node2 = TextNode(text="", id_="") set relationships node1.relationships[NodeRelationship.NEXT] = RelatedNodeInfo( node_id=node2.node_id ) node2.relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo( node_id=node1.node_id ) nodes = [node1, node2] {% endhighlight %} 또한 아래와 같이 node간의 종속적 정보를 추가 할 수 있습니다. {% highlight python %} node2.relationships[NodeRelationship.PARENT] = RelatedNodeInfo( node_id=node1.node_id, metadata={“key”: “val”} ) {% endhighlight %} 노드는 다음의 방식으로 id를 직접 주입할 수 있습니다. 이러한 id 값은 다양한 역활을 할 수 있습니다. {% highlight python %} node.node_id = “My new node_id!” {% endhighlight %} Advance nodes advance(1)
AI
/
NLP
/
llama index
· 2024-03-08
Llamaindex documents Advance(1)
documents loaders flat document documents는 다양한 형태를 가진 파일들을 불러오는데 사용이 될 수 있으나, 단순한 파일을 불러올 수도 있습니다. 단순한 파일을 불러올때는 아래와 같이 단순한 방식이 제공됩니다. {% highlight python %} from llama_index.readers.file import FlatReader from pathlib import Path md_docs = FlatReader().load_data(Path(“./test.md”)) {% endhighlight %} other document loader other document loader metadata extraction usage pattern 다음과 같이 LLM을 사용하여 metadata를 추출해낼 수 있습니다. {% highlight shell %} pip install llama-index-extractors-entity {% endhighlight %} {% highlight python %} import os OPENAI_API_TOKEN = “sk-“ os.environ[“OPENAI_API_KEY”] = OPENAI_API_TOKEN llm = OpenAI(temperature=0.1, model=”gpt-3.5-turbo”, max_tokens=512) from llama_index.core.extractors import ( TitleExtractor, QuestionsAnsweredExtractor, SummaryExtractor, KeywordExtractor, BaseExtractor, ) from llama_index.extractors.entity import EntityExtractor class CustomExtractor(BaseExtractor): def extract(self, nodes): metadata_list = [ { “custom”: ( node.metadata[“document_title”] + “\n” + node.metadata[“excerpt_keywords”] ) } for node in nodes ] return metadata_list title_extractor = TitleExtractor(nodes=5) qa_extractor = QuestionsAnsweredExtractor(questions=3) summary_extractor = SummaryExtractor(summaries=[“prev”, “self”,”next”]) keyword_extractor = KeywordExtractor(keywords=10, llm=llm), custom_extractor = CustomExtractor() entity_extractor = EntityExtractor( prediction_threshold=0.5, label_entities=False, # include the entity label in the metadata (can be erroneous) device=”cpu”, # set to “cuda” if you have a GPU ) {% endhighlight %} pipeline nodes advance(1)까지 확인 이후 pipeline을 아래와 같이 도입 가능합니다. document node pipeline
AI
/
NLP
/
llama index
· 2024-03-07
Llamaindex documents
what is documents documents는 다양한 NLP process에서 사용할 문서를 불러오는 방식을 말합니다. How to use documents tutorial documents를 사용하는데 있어서 가장 기초적인 예시는 아래와 같습니다. {% highlight python %} from llama_index.core import Document, VectorStoreIndex document = Document.example() build index index = VectorStoreIndex.from_documents(documents) {% endhighlight %} read documents documents를 사용하는방법은 다양하게 존재합니다. 다음은 documents를 만드는 두가지 방법을 나타냅니다. Directory Reader 다음의 방식은 directory에 있는 문서들을 읽는 방식입니다. 해당방식은 지정한 폴더에 있는 문서는 읽을 수 있으나 하위 폴더에 있는 문서를 읽을 수는 없습니다. {% highlight python %} from llama_index.core import SimpleDirectoryReader documents = SimpleDirectoryReader(“./data”).load_data() {% endhighlight %} custom setting 다음의 방식은 사용자가 직접 지정한 문서들을 입력하는 방식입니다. 이는 text를 하나씩 지정해야하는 방식입니다. {% highlight python %} from llama_index.core import Document text_list = [text1, text2, …] documents = [Document(text=t) for t in text_list] {% endhighlight %} documents metadata 문서들은 다양한 metadata를 가지게 됩니다. 해당하는 metadata는 NLP process에서 중요한 역활을 하게 되며 해당하는 값들을 상세히 지정하는것은 중요합니다. add metadata(pre read) document constructor를 만들기 이전에 metadata를 지정하는 방식은 다음과 같습니다. W. dir reader 다음과 같이 dir reader를 사용하면서 metadata들을 지정 할 수 있습니다. {% highlight python %} from llama_index.core import SimpleDirectoryReader filename_fn = lambda filename: {“file_name”: filename} automatically sets the metadata of each document according to filename_fn documents = SimpleDirectoryReader( “./data”, file_metadata=filename_fn, filename_as_id=True, ).load_data() {% endhighlight %} W. custom reader 다음과 같이 custom reader를 사용하면서 metadata들을 지정 할 수 있습니다. {% highlight python %} document = Document( text=”text”, metadata={ “filename”: “", "category": "", "doc_id": ""}, ) {% endhighlight %} add metadata(after read) document constructor를 만든 이후에 잘못된 metadata를 변경하는 방식은 다음과 같습니다. {% highlight python %} document.metadata = {“filename”: “"} document.doc_id = "My new document id!" {% endhighlight %} advance metadata setting 다양한 metadata는 NLP process에 다양한 강점을 가질 수 있지만, 오히려 과한 정보로 혼란을 줄 수 있습니다. 이럴 경우 필요없는 정보를 배제할 수 있습니다. 다음은 LLM이 metadata를 활용하는지 설정하는것입니다. {% highlight python %} document.excluded_llm_metadata_keys = [“file_name”] {% endhighlight %} 다음은 embedding 과정에서 metadata를 활용하는지 설정하는것입니다. {% highlight python %} document.excluded_embed_metadata_keys = [“file_name”] {% endhighlight %} 다음은 위에서 설정한 metadata 배제를 한 이외의 값이 어떻게 보여지는지 확인하는 방법입니다. {% highlight python %} from llama_index.core.schema import MetadataMode print(document.get_content(metadata_mode=MetadataMode.LLM)) print(document.get_content(metadata_mode=MetadataMode.EMBED)) {% endhighlight %} 이외에도 metadata의 format을 설정 가능합니다. 다음 예시에서는 format을 사용한 전체적인 사용법을 나타냅니다. advance metadata setting example {% highlight python %} from llama_index.core import Document from llama_index.core.schema import MetadataMode document = Document( text=”This is a super-customized document”, metadata={ “file_name”: “super_secret_document.txt”, “category”: “finance”, “author”: “LlamaIndex”, }, excluded_llm_metadata_keys=[“file_name”], metadata_seperator=”::”, metadata_template=”{key}=>{value}”, text_template=”Metadata: {metadata_str}\n—–\nContent: {content}”, ) print( “The LLM sees this: \n”, document.get_content(metadata_mode=MetadataMode.LLM), ) print( “The Embedding model sees this: \n”, document.get_content(metadata_mode=MetadataMode.EMBED), ) {% endhighlight %} Advance documents advance(1)
AI
/
NLP
/
llama index
· 2024-03-06
Llamaindex intro
How to start 라마 인덱스를 활용하는 방법은 3가지가 있습니다. 첫번째는 initial setting, 두번째는 custom setting, 세번째는 source에서 직접 설치하는 방법입니다. init install 기초적인 설치방법으로 OpenAI와 같이 대표적인 LLM을 활용하는데 있어서 적절합니다. {% highlight shell %} pip install llama-index {% endhighlight %} custom install 개별적 모델을 활용하기 위한 설치방법으로 OpenAI와 같이 대표적인 LLM 이외에도 다양한 모델을 Ollama 또는 huggingface등에서 가져와서 활용이 가능합니다. {% highlight shell %} pip install llama-index-core llama-index-readers-file llama-index-llms-ollama llama-index-embeddings-huggingface {% endhighlight %} source install 위 두가지 설치가 작동이 되지 않거나, source에서 직접 원하는것들만 설치를 하고 싶을때 사용할 수 있습니다. {% highlight shell %} git clone https://github.com/jerryjliu/llama_index.git pip install -e llama-index-integrations/llms/llama-index-llms-ollama {% endhighlight %} simple start example 아래의 예시는 RAG를 활용한 예시입니다. ./data/paul_graham/ 폴더를 생성하여 RAG에 사용할 txt 데이터를 넣으면 됩니다. 또는 아래의 코드를 통하여 공식적인 예시 데이터를 사용할 수 있습니다. {% highlight shell %} mkdir -p ‘data/paul_graham/’ wget ‘https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt’ -O ‘data/paul_graham/paul_graham_essay.txt’ {% endhighlight %} W. OpenAI OpenAI를 사용하여 활용을 하려면 우선 아래와 같이 환경설정이 필요합니다. {% highlight shell %} export OPENAI_API_KEY=XXXXX # linux set OPENAI_API_KEY=XXXXX # window {% endhighlight %} 이후 아래의 코드로 간단하게 활용이 가능합니다. {% highlight python %} import os from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, load_index_from_storage, ) check if local storage already exists PERSIST_DIR = “./storage” if not os.path.exists(PERSIST_DIR): # load the documents and create the index documents = SimpleDirectoryReader(“./data/paul_graham/”).load_data() index = VectorStoreIndex.from_documents(documents) # store it for later index.storage_context.persist(persist_dir=PERSIST_DIR) else: # load the existing index storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR) index = load_index_from_storage(storage_context) Either way we can now query the index query_engine = index.as_query_engine() response = query_engine.query(“{Question}”) print(response) {% endhighlight %} W. Custom model(ollama) ollama를 사용하기 위하여 기본 설치 및 사용법을 알아야합니다. 사용법은 아래를 참고하면 됩니다. how to use ollama ollama 사용법 숙지 이후 사용할 모델을 다운 받고 아래의 코드로 진행이 가능합니다. {% highlight python %} from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings from llama_index.core.embeddings import resolve_embed_model from llama_index.llms.ollama import Ollama documents = SimpleDirectoryReader(“./data/paul_graham/”).load_data() bge embedding model Settings.embed_model = resolve_embed_model(“local:BAAI/bge-small-en-v1.5”) ollama Settings.llm = Ollama(model=, request_timeout=30.0) index = VectorStoreIndex.from_documents( documents, ) query_engine = index.as_query_engine() response = query_engine.query(“{Question}”) print(response) {% endhighlight %} W. Custom model(hugging face) hugging face를 사용하기 위하여 기본 설치 및 사용법을 알아야합니다. 사용법은 아래를 참고하면 됩니다. how to use hugging face hugging face 사용법 숙지 이후 추가적으로 아래의 필요 모듈을 다운받아야 합니다. {% highlight shell %} pip install llama-index-llms-huggingface pip install llama-index {% endhighlight %} 이후 아래의 코드로 실행해 볼 수 있습니다. {% highlight python %} setup prompts - specific to StableLM from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings, PromptTemplate from llama_index.llms.huggingface import HuggingFaceLLM import torch load documents documents = SimpleDirectoryReader(“./data/paul_graham/”).load_data() This will wrap the default prompts that are internal to llama-index taken from https://huggingface.co/Writer/camel-5b-hf query_wrapper_prompt = PromptTemplate( “Below is an instruction that describes a task. “ “Write a response that appropriately completes the request.\n\n” “### Instruction:\n{query_str}\n\n### Response:” ) llm = HuggingFaceLLM( context_window=2048, max_new_tokens=256, generate_kwargs={“temperature”: 0.25, “do_sample”: False}, query_wrapper_prompt=query_wrapper_prompt, tokenizer_name=”Writer/camel-5b-hf”, model_name=”Writer/camel-5b-hf”, device_map=”auto”, tokenizer_kwargs={“max_length”: 2048}, # uncomment this if using CUDA to reduce memory usage # model_kwargs={“torch_dtype”: torch.float16} ) Settings.chunk_size = 512 Settings.llm = llm index = VectorStoreIndex.from_documents(documents) set Logging to DEBUG for more detailed outputs query_engine = index.as_query_engine() response = query_engine.query(“What did the author do growing up?”) print(response) {% endhighlight %} streaming service 스트리밍 서비스로 작동을 하기 위하여 index.as_query_engine()에서 부터 아래와 같이 변경을 해주면 됩니다. {% highlight python %} query_engine = index.as_query_engine(streaming=True) set Logging to DEBUG for more detailed outputs response_stream = query_engine.query(“What did the author do growing up?”) can be slower to start streaming since llama-index often involves many LLM calls response_stream.print_response_stream() can also get a normal response object response = response_stream.get_response() print(response) {% endhighlight %}
AI
/
NLP
/
llama index
· 2024-03-05
<
>
Touch background to close